package com.yjh.auth.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author guozh @date 2019/5/30
 * @Description
 */
@Log4j2
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig {

    private Duration baseBizDataLiveTime = Duration.ZERO;

    @Bean
    @Primary
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        return RedisCacheManager.create(factory);
    }

    @Bean(name = "bizRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 1 创建 RedisTemplate 模板
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 2 关联 RedisConnectionFactory
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());

//		Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<>(Object.class);
//		template.setDefaultSerializer(ser);
        log.debug("自定义RedisCacheManager加载完成");
        return redisTemplate;
    }

    /** 缓存管理器 */
    @Bean(name = "bizCacheManager")
    public CacheManager bizCacheManager(RedisConnectionFactory redisConnectionFactory) {

        // 设置属性时必须接受返回值，否则无效
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 设置存活时间
                .entryTtl(this.baseBizDataLiveTime)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
//				.disableCachingNullValues();	// 开启后对象中的字段为空也无法通过

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();

        log.debug("自定义RedisCacheManager加载完成");
        return redisCacheManager;
    }

    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    private RedisSerializer<Object> valueSerializer() {
        // 1 创建对象映射设置
        ObjectMapper om = new ObjectMapper();
        // 2 设置可见度
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 3 解决 jackson2 无法反序列化 LocalDateTime 的问题
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        // 4 启动默认的类型
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        // 5 创建序列化类对象
        GenericJackson2JsonRedisSerializer serializer
                = new GenericJackson2JsonRedisSerializer(om);

        return serializer;
    }

    public void setBaseBizDataLiveTime(Duration baseBizDataLiveTime) {
        this.baseBizDataLiveTime = baseBizDataLiveTime;
    }
}

